﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;

namespace LargeFileUpload.Web
{
    /// <summary>
    /// Summary description for StoreFile
    /// </summary>
    public class StoreFile : IHttpHandler
    {

        private const long READ_BUFFER_LEN = 57344;

        public void ProcessRequest(HttpContext context)
        {
            context.Server.ScriptTimeout = 10;
            context.Response.ContentType = "text/plain";
            string check = context.Request["filestream"];
            int Offset = Convert.ToInt32(context.Request["offset"]);

            //if (Offset == 3)
            //    throw new Exception("Some Web Error just happened");
            context.Response.Write(Offset.ToString());

            check = Regex.Replace(check, " ", "+");
            byte[] bytes = Convert.FromBase64String(check);
            string fileinfo = context.Server.MapPath(context.Request["fileinfo"]);

            FileStream fs = new FileStream(fileinfo, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write);
            fs.Seek(READ_BUFFER_LEN * Offset, SeekOrigin.Begin);
            fs.Write(bytes, 0, bytes.Length);
            fs.Close();
            fs.Dispose();
            //System.Threading.Thread.Sleep(500);
        }

        private void fileit()
        {
            }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}